<template>
  <div class="login" :style="loginStyle">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">{{title}}</h3>
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          type="text"
          auto-complete="off"
          placeholder="账号"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaEnabled">
        <div class="captcha-container">
          <el-input
            v-model="loginForm.code"
            auto-complete="off"
            placeholder="验证码"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img"/>
          </div>
        </div>
      </el-form-item>
      <el-form-item prop="authCode" v-if="requiresAuthorization">
        <el-input
          v-model="loginForm.authCode"
          type="password"
          auto-complete="off"
          placeholder="授权码"
          show-password
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="lock" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div style="float: right;" v-if="register">
          <router-link class="link-type" :to="'/register'">立即注册</router-link>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getCodeImg } from "@/api/login"
import Cookies from "js-cookie"
import { encrypt, decrypt } from '@/utils/jsencrypt'
import { getFileDisplayUrl } from '@/api/system/fileinfo'
import { checkAuthorizationStatus } from '@/api/system/authorization'

export default {
  name: "Login",
  computed: {
    // 动态计算登录背景样式
    loginStyle() {
      if (this.backgroundImage) {
        return {
          backgroundImage: `url(${this.backgroundImage})`,
          backgroundSize: 'cover',
          backgroundPosition: 'center',
          backgroundRepeat: 'no-repeat'
        }
      }
      return {}
    }
  },
  data() {
    return {
      title: "运销系统", // 默认标题，将通过API动态获取
      backgroundImage: "", // 动态背景图片
      codeUrl: "",
      requiresAuthorization: false, // 是否需要授权码
      loginForm: {
        username: "",
        password: "",
        rememberMe: true,
        code: "",
        uuid: "",
        authCode: "" // 授权码
      },
      loginRules: {
        username: [
          {required: true, trigger: "blur", message: "请输入您的账号"}
        ],
        password: [
          {required: true, trigger: "blur", message: "请输入您的密码"}
        ],
        code: [{required: true, trigger: "change", message: "请输入验证码"}],
        authCode: [{required: true, trigger: "blur", message: "请输入系统授权码"}]
      },
      loading: false,
      // 验证码开关
      captchaEnabled: false,
      // 注册开关
      register: true,
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    this.getCode()
    this.getCookie()
    this.getSystemTitle()
    this.getBackgroundImage()
    this.checkSystemAuthorizationStatus()
  },
  methods: {
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img
          this.loginForm.uuid = res.uuid
        }
      })
    },
    getCookie() {
      const username = Cookies.get("username")
      const password = Cookies.get("password")
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, {expires: 30})
            Cookies.set("password", encrypt(this.loginForm.password), {expires: 30})
            Cookies.set('rememberMe', this.loginForm.rememberMe, {expires: 30})
          } else {
            Cookies.remove("username")
            Cookies.remove("password")
            Cookies.remove('rememberMe')
          }
          this.$store.dispatch("Login", this.loginForm).then(() => {
            this.$router.push({path: this.redirect || "/"}).catch(() => {
            })
          }).catch(() => {
            this.loading = false
            if (this.captchaEnabled) {
              this.getCode()
            }
          })
        }
      })
    },
    // 获取系统标题
    getSystemTitle() {
      // 从系统配置中获取标题，如果没有配置则使用环境变量或默认值
      this.getConfigKey("sys.index.title").then(response => {
        if (response.msg) {
          this.title = response.msg
        } else {
          // 如果配置中没有找到，则使用环境变量
          this.title = process.env.VUE_APP_TITLE || "运销系统"
        }
      }).catch(() => {
        // 如果API调用失败，则使用环境变量作为备用
        this.title = process.env.VUE_APP_TITLE || "运销系统"
      })
    },
    // 获取系统背景图片
    getBackgroundImage() {
      // 从系统配置中获取背景图片的文件ID
      this.getConfigKey("sys.login.backgroundImage").then(response => {
        if (response.msg && response.msg.trim()) {
          // 如果是数字，说明是文件ID
          const fileId = response.msg.trim()
          if (/^\d+$/.test(fileId)) {
            this.backgroundImage = getFileDisplayUrl(fileId)
          } else {
            // 如果不是纯数字，可能是旧的base64格式，直接使用
            this.backgroundImage = response.msg
          }
        }
      }).catch(() => {
        // 如果API调用失败或没有配置，使用默认背景
        console.log('使用默认背景图片')
      })
    },
    // 检查系统授权状态
    checkSystemAuthorizationStatus() {
      checkAuthorizationStatus().then(response => {
        if (response.data && response.data.isAuthorized === false) {
          this.requiresAuthorization = true
        } else {
          this.requiresAuthorization = false
        }
      }).catch(() => {
        // 如果接口调用失败，不显示授权码输入框
        this.requiresAuthorization = false
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/yxxt2.jpg"); /* 默认背景，当没有动态背景时使用 */
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  padding: 20px;

  @media (max-width: 768px) {
    padding: 10px;
    background-position: center;
  }
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;

  @media (max-width: 768px) {
    font-size: 24px;
    margin-bottom: 25px;
  }
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  z-index: 1;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  @media (max-width: 768px) {
    width: 100%;
    padding: 20px;
    margin-right: 0;
  }

  @media (max-width: 480px) {
    padding: 15px;
  }

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.captcha-container {
  display: flex;
  gap: 10px;

  .el-input {
    flex: 1;
  }

  @media (max-width: 480px) {
    flex-direction: column;

    .login-code {
      width: 100%;
      height: 45px;
      margin-top: 10px;
    }
  }
}

.login-code {
  width: 33%;
  height: 38px;

  @media (max-width: 480px) {
    width: 40%;
  }

  img {
    cursor: pointer;
    vertical-align: middle;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;

  @media (max-width: 480px) {
    height: 45px;
  }
}

// 移动端专用样式
@media (max-width: 768px) {
  .login-form {
    .el-form-item {
      margin-bottom: 20px;
    }

    .el-button {
      height: 45px;
      font-size: 16px;
    }
  }

  .el-checkbox {
    display: block;
    margin-bottom: 20px !important;
  }
}

@media (max-width: 480px) {
  .login-form {
    .el-form-item__content {
      display: flex;
      flex-direction: column;
    }
  }
}
</style>
